<?php

class Application_Model_TagService extends Base_Service
{
   
	public function create($tag) {		
		$db = $this->getDbAdapter();
		
		$row = array ( 
		'tag' => $tag
		);
		$this->logger->debug(__METHOD__. '   ' .$row);		
		$rows_affected = $db->insert('tag', $row);
		$last_insert_id = $db->lastInsertId();
		$this->logger->debug(__METHOD__. '   ' .$last_insert_id);
		
		return $last_insert_id;
		
	}
	
	
 	public function getTagId($tag)
	{
		$table = new Application_Model_DbTable_Tag();
		$resultSet = $table-> fetchAll("tag='".$tag."'",null,1);
		
		foreach ($resultSet as $row) {
			return $row->tid;			
		}
		return -1;
	}
	/**
	 * Not used tags will not be selected
	 */
	public function getAllTags($uid){
		$db = Zend_Db_Table::getDefaultAdapter();
		$sql = "select a.*, count(a.tid) count"
		." from tag a, content_tag b"
		." where a.tid = b.tid";
		if ($uid) {
			$sql = $sql." and exists(select 1 from blog c where c.bid=b.content_id and c.owner_id=".$uid.")";
		}
		$sql = $sql." group by a.tid order by a.tag";
		$this->logger->debug(__METHOD__." sql: ".$sql);
		return $db->fetchAll($sql);
	}
	
	public function getTag($tagId)
	{
		if ($tagId) {
			$table = new Application_Model_DbTable_Tag();
			$resultSet = $table-> fetchAll("tid='".$tagId."'",null,1);
			
			foreach ($resultSet as $row) {
				return $row->tag;			
			}
		}	
	}
	protected static $_instance = null;
	public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}

